package blockchain

import (
	"errors"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

var (
	Sdk           *fabsdk.FabricSDK
	configPath    = "/home/dapp/fabric-cluster/application/config.yaml"
	channelName   = "mychannel"
	user          = "Admin"
	chainCodeName = "basic"
	endpoints     = []string{"peer0.org1.example.com", "peer0.org2.example.com"}
)

func InitSDK() error {
	var err error
	Sdk, err = fabsdk.New(config.FromFile(configPath))
	if err != nil {
		// fmt.Printf("init sdk err: %v", err)
		return errors.New("Init sdk fail!")
	}
	return nil
}

func ChannelExecute(sdk *fabsdk.FabricSDK, fcn string, args [][]byte) (channel.Response, error) {
	ctx := sdk.ChannelContext(channelName, fabsdk.WithUser(user))
	cli, err := channel.New(ctx)
	if err != nil {
		return channel.Response{}, err
	}
	resp, err := cli.Execute(channel.Request{
		ChaincodeID: chainCodeName,
		Fcn:         fcn,
		Args:        args,
	}, channel.WithTargetEndpoints(endpoints...))
	if err != nil {
		return channel.Response{}, err
	}
	return resp, nil
}

func ChannelQuery(sdk *fabsdk.FabricSDK, fcn string, args [][]byte) (channel.Response, error) {
	ctx := sdk.ChannelContext(channelName, fabsdk.WithUser(user))
	cli, err := channel.New(ctx)
	if err != nil {
		return channel.Response{}, err
	}
	resp, err := cli.Query(channel.Request{
		ChaincodeID: chainCodeName,
		Fcn:         fcn,
		Args:        args,
	}, channel.WithTargetEndpoints(endpoints...))
	if err != nil {
		return channel.Response{}, err
	}
	return resp, nil
}
